﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ExameRegister.Views;
using System.Windows.Markup;
using ExameRegister.Model;
using System.Collections.ObjectModel;
using System.Windows.Browser;
using System.IO;

namespace ExameRegister
{
    public partial class InfomationControl : UserControl, IAsyncCtrl, IReturnListenerc
    {
        //private WCFService.WCFServiceClient client = null;
        ServiceUtility su = new ServiceUtility();
        public InfomationControl(PublicOfficialInfo pi)
        {
            InitializeComponent();
            su.OnCompletedCallService += new EventHandler<WCFEvent>(su_OnCompletedCallService);
            //client = new WCFService.WCFServiceClient();
            //client.GetPublicOfficialInfoCompleted += new EventHandler<WCFService.GetPublicOfficialInfoCompletedEventArgs>(client_GetPublicOfficialInfoCompleted);
            //client.GetPublicOfficialInfoAsync("Status = 1  order by inputtime desc");
            su.CallService("ExameRegister.BO.LoginBO", "GetPublicOfficialInfo", new object[] { "Status = 1  order by inputtime desc" }, this, "GetPublicOfficialInfo");
        }

        void su_OnCompletedCallService(object sender, WCFEvent e)
        {
            string us = e.UserState as string;
            switch (us)
            {
                case "GetPublicOfficialInfo":
                    ObservableCollection<PublicOfficialInfo> collection = Utility.ConvertFromJson<ObservableCollection<PublicOfficialInfo>>(e.Result);
                    entity = collection.FirstOrDefault();
                    if (entity != null)
                    {
                        if (Sessions.Session.Keys.Contains(Sessions.EXAMENATION))
                            Sessions.Session.Remove(Sessions.EXAMENATION);
                        Sessions.Session.Add(Sessions.EXAMENATION, entity.ID);
                        try
                        {
                            rtb.SetXaml(entity.Infomation);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            MessageBox.Show(entity.Infomation);
                            //SilverlightMessageBoxLibrary.Message.InfoMessage(entity.Infomation);
                        }
                        if (Sessions.Session.Keys.Contains(Sessions.EXAMENATIONTYPE))
                            Sessions.Session.Remove(Sessions.EXAMENATIONTYPE);
                        Sessions.Session.Add(Sessions.EXAMENATIONTYPE, entity.Type);
                        su.CallService("ExameRegister.BO.LoginBO", "GetFiles", new object[] { entity.ID }, this, "GetFiles");
                    }
                    break;
                case "GetFiles":
                    var result = Utility.ConvertFromJson<List<Files>>(e.Result);
                    downLoadFile.ItemsSource = result;
                    break;
                case "DownLoadFile":

                    if (_openFile != null)
                    {                        
                        ObservableCollection<byte> bs = Utility.ConvertFromJson<ObservableCollection<byte>>(e.Result);
                        if (bs != null && bs.Count > 0)
                        {
                            if(stream == null)
                                stream = _openFile.OpenFile();
                            stream.Write(bs.ToArray<byte>(), 0, bs.Count);
                            stream.Close();
                            stream.Dispose();
                        }
                    }
                    break;
            }
        }
        private Stream stream = null;
        private PublicOfficialInfo _entity;
        private PublicOfficialInfo entity
        {
            get { return _entity; }
            set
            {
                if (value != null)
                {
                    //hbDownload.IsEnabled = true;
                    hbRegister.IsEnabled = true;
                    _entity = value;
                }
            }
        }
        //void client_GetPublicOfficialInfoCompleted(object sender, WCFService.GetPublicOfficialInfoCompletedEventArgs e)
        //{
        //    if (e.Result != null)
        //    {
        //        entity = e.Result.FirstOrDefault();
        //        if (entity != null)
        //        {
        //            rtb.Xaml = entity.Infomation;
        //        }
        //    }
        //}

       
        public string Title
        {
            get
            ;
            set
            ;
        }

        public bool PageLoaded
        {
            get
            ;
            set
            ;
        }

        public Assert.NavMoveSwitch Nav
        {
            get
            ;
            set
            ;
        }

        public void BeginReturn()
        {
            return;
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            PositionList view = new PositionList(entity.ID);
            view.Nav = this.Nav;
            ReturnAsyncCtrl page = new ReturnAsyncCtrl(view) { Nav = this.Nav, PrevPage = this, Title = "简历列表" };
            this.Nav.SetNextPage(page);
            this.Nav.MoveNext();
        }

        private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
        {
            //RegisterPositionsControl view = new RegisterPositionsControl();
            //view.Nav = this.Nav;
            //ReturnAsyncCtrl page = new ReturnAsyncCtrl(view) { Nav = this.Nav, PrevPage = this, Title = entity.Name };
            //this.Nav.SetNextPage(page);
            //this.Nav.MoveNext();
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //System.IO.Stream stream = null;
        private SaveFileDialog _openFile = null;
        private void HyperlinkButton_Click_2(object sender, RoutedEventArgs e)
        {
            _openFile = null;
            string display = ((sender as System.Windows.Controls.HyperlinkButton).DataContext as ExameRegister.Model.Files).Displayname;
            string[] str = display.Split('.');
            string filter = string.Empty;
            if (str.Length > 0)
                filter = "(*." + str[str.Length - 1] + ")|*." + str[str.Length - 1];
            var openfile = new SaveFileDialog() { Filter = filter };
            if (openfile.ShowDialog() == false)
                return;
            _openFile = openfile;
            //stream = openfile.OpenFile();
            //listBytes.Clear();
            string filename = ((sender as System.Windows.Controls.HyperlinkButton).DataContext as ExameRegister.Model.Files).filename;
            su.OnCompletedCallService -= new EventHandler<WCFEvent>(su_OnCompletedCallService);
            su.OnCompletedCallService -= new EventHandler<WCFEvent>(su_OnCompletedCallService2);
            su.OnCompletedCallService+=new EventHandler<WCFEvent>(su_OnCompletedCallService2);
            UploadFileInfo info = new UploadFileInfo() { key = "file", Name = filename, Size = 1600,start= 0, IsFinished = false };
            su.CallService("ExameRegister.BO.LoginBO", "DownLoadFile", new object[] { info}, this, "DownLoadFile");
        }
        //private List<byte> listBytes = new List<byte>();
        void su_OnCompletedCallService2(object sender, WCFEvent e)
        {
            UploadFileInfo info = Utility.ConvertFromJson<UploadFileInfo>(e.Result);
            if (info == null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("下载的文件不存在");
                return;
            }

            if (stream == null)
                stream = _openFile.OpenFile();
            if (info.IsFinished == true)
            {
                if (info.Context != null)
                    stream.Write(info.Context, 0, info.Context.Length);
                stream.Close();
                SilverlightMessageBoxLibrary.Message.InfoMessage("下载完成");

            }
            else
            {
                info.start += info.Context.Length;
                stream.Write(info.Context, 0, info.Context.Length);
                su.CallService("ExameRegister.BO.LoginBO", "DownLoadFile", new object[] { info }, this, "DownLoadFile");
            }
        }
    }
}
